package com.yinuo.common;

import com.yinuo.entity.GlobalContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.MessageFormat;
import java.util.*;
import java.util.List;

/**
 * 系统服务员
 * 解释：勤杂工
 */
public class SystemWaiter {

    private static Logger logger = LoggerFactory.getLogger(SystemWaiter.class);

    /**
     * 上传的图片文件目录
     */
    public static final String imageFolder = "uploadedFiles/ueditor/jsp/upload/image";

    /**
     * 打开浏览器
     */
    public static void openBrowser(String url){
        if(Desktop.isDesktopSupported()){
            Desktop desktop = Desktop.getDesktop();
            try {
                desktop.browse(new URI(url));
            } catch (Exception e) {
                logger.error("Open desktop browser failed ! You can manually open it.");
            }
        }else{
            Runtime runtime = Runtime.getRuntime();
            try {
                //runtime.exec("cmd /c start http://localhost");
                runtime.exec(MessageFormat.format("explorer {0}",url));
            } catch (IOException e) {
                logger.error("Open desktop browser failed ! You can manually open it.");
            }
        }
    }

    /**
     * 清理没有任何引用的file
     */
    public static void clearImageFile(List<String> referenList){
        if(referenList==null)return;
        String uploadRootPath = getFilesRootPath()+imageFolder;
        List<String> folderList = FileUtil.getAllFullPathFolderName(uploadRootPath,new ArrayList<String>(20));
        if(folderList==null)return;
        List<String> existedFiles = new ArrayList<String>(20);
        for(String s:folderList){
           List<String> fileNames = FileUtil.getAllFullPathFileNames(s);
           for(String ss:fileNames){
               existedFiles.add(ss);
           }
        }
        logger.info(String.format("[********** Image existed in local(%d) : %s**********]",existedFiles.size(),existedFiles.toString()));
        List<String> tempList = new ArrayList<String>(20);
        for(String s:referenList){
            s = s.replaceAll("/","\\\\");
            for(int i=0;i<existedFiles.size();i++){
                String temp = existedFiles.get(i);
                if(temp.contains(s)){
                    tempList.add(temp);
                }
            }
        }
        existedFiles.removeAll(tempList);
        logger.info(String.format("[********** Image not reference in local(%d) : %s**********]",existedFiles.size(),existedFiles.toString()));
        for(String s:existedFiles){
            boolean b = FileUtil.deleteFile(s);
            if(b){
                logger.info(String.format("[******** Image (%s) is deleted ! ********]",s));
            }else{
                logger.info(String.format("[******** Image (%s) delete failed ! ********]",s));
            }
        }
    }

    /**
     * 项目中文件根目录
     */
    public static String getFilesRootPath(){
        String filePath = System.getProperty("user.dir")+GlobalContext.DOC_SUMMAY_FILES;
        File filePathObj = new File(filePath);
        if(!filePathObj.exists()){
            logger.info(String.format("%s folder is not exists and it created.",filePath));
            filePathObj.mkdirs();
        }
        return filePath;
    }
}
